<template>
  <div class="myPage">
    <div class="row search-row">
      <el-form ref="formRef" :model="searchForm.condition" inline label-width="auto">
        <el-form-item label="项目编号" prop="projectNo" style="width: 21%">
          <el-input v-model="searchForm.condition.projectNo" placeholder="支持模糊搜索"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName" style="width: 21%">
          <el-input v-model="searchForm.condition.projectName" placeholder="支持模糊搜索"/>
        </el-form-item>
        <el-form-item label="申报单号" prop="applyNo" style="width: 21%">
          <el-input v-model="searchForm.condition.applyNo" placeholder="支持模糊搜索"/>
        </el-form-item>
        <el-form-item label="申请时间" prop="applyTime" style="width: 25%">
          <el-date-picker type="daterange" value-format="YYYY-MM-DD" v-model="searchForm.condition.applyTime" style="width: 100%;"/>
        </el-form-item>
        <el-form-item label="施工单位" prop="constructionUnitName" style="width: 21%">
          <el-input v-model="searchForm.condition.constructionUnitName" placeholder="支持模糊搜索"/>
        </el-form-item>
        <el-form-item label="涉及作业" prop="specialJobType" style="width: 21%">
          <el-tree-select multiple collapse-tags v-model="searchForm.condition.specialJobType" :data="options.projectWorkTypeOptions" node-key="value" placeholder="请选择"
                          show-checkbox :props="options.projectWorkTypeTreeProps" class="tree-select" style="width: 100%;"/>
        </el-form-item>
        <el-form-item label="项目单位" prop="projectUnitName" style="width: 21%">
          <el-input v-model="searchForm.condition.projectUnitName" placeholder="支持模糊搜索"/>
        </el-form-item>
        <el-form-item label="状态" prop="state" style="width: 25%">
          <el-select v-model="searchForm.condition.state" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in options.stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="航站楼" prop="location" style="width: 44%">
          <el-checkbox :indeterminate="isIndeterminateLocation" v-model="checkAllLocation" @change="handleCheckAllChangeLocation">全选 {{ locationNumTotal }}</el-checkbox>
          <div style="margin-left: 20px;"></div>
          <el-checkbox-group v-model="searchForm.condition.location" @change="handleCheckedChangeLocation">
            <el-checkbox v-for="item in options.locationO" :label="item.value" :key="item.value">{{item.label}} {{ item.num }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
       
        <el-form-item label="项目类型" prop="projectType">
          <el-checkbox :indeterminate="isIndeterminateProjectType" v-model="checkAllProjectType" @change="handleCheckAllChangeProjectType">全选 {{projectTypeNumTotal}}</el-checkbox>
          <div style="margin-left: 20px;"></div>
          <el-checkbox-group v-model="searchForm.condition.projectType" @change="handleCheckedChangeProjectType">
            <el-checkbox v-for="item in options.projectTypeO" :label="item.value" :key="item.value">{{item.label}} {{ item.num }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div class="btnBox">
        <el-button @click="handleReset">清空</el-button>
        <el-button type="primary" @click="handleQuery" :disabled="loading">查询</el-button>
      </div>
    </div>

    <div class="row table-row">
      <div class="table-head">
        <span>数据列表</span>
        <div>
          <el-button @click="handleExportList" :disabled="exportLoading">导出</el-button>
          <el-button type="primary" @click="goCreate">新增施工申请</el-button>
        </div>
      </div>
      <el-table max-height="1500"
    :height="550" :data="tableData" class="project-application-table" v-loading="loading">
        <el-table-column label="序号" prop="index">
          <template v-slot="{$index}">
            {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column width="120" show-overflow-tooltip label="项目类型" prop="projectType" :formatter="(row, column, cellValue) => dicFormatter(options.projectTypeO, cellValue)"/>
        <el-table-column width="200" show-overflow-tooltip label="项目名称" prop="projectName"/>
        <el-table-column width="200" show-overflow-tooltip label="项目单位" prop="projectUnitName"/>
        <el-table-column width="200" show-overflow-tooltip label="项目编号" prop="projectNo"/>
        <el-table-column class="cell" width="200"  label="施工作业内容" prop="constructionOperationContent">
        <template v-slot="{row}">
            <el-popover
              placement="top-start"
              :width="700"
              trigger="hover"
              :content="row.constructionOperationContent"
              :disabled="!isShowTooltip"
              effect="dark"
            >
              <template #reference>
                <div class="hide" @mouseover="onMouseOver($event,row.constructionOperationContent)">
                <span>{{ row.constructionOperationContent || '-' }}</span>
              </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column width="120" show-overflow-tooltip label="项目负责人" prop="constructionChargePersonName"/>
        <el-table-column width="200" show-overflow-tooltip label="施工单位" prop="constructionUnitName"/>
        <el-table-column width="200" show-overflow-tooltip label="涉及作业" prop="specialJobType"/>
        <el-table-column width="200" show-overflow-tooltip label="申报单号" prop="applyNo"/>
        <el-table-column width="200" show-overflow-tooltip label="申请时间" prop="applyTime"/>
        <el-table-column width="120" show-overflow-tooltip label="状态" prop="state" :formatter="(row, column, cellValue) => dicFormatter(options.stateOptions, cellValue)"/>
        <el-table-column width="200" label="操作" fixed="right">
          <template v-slot="{row}">
            <el-button type="text" @click="goDetail(row)">查看</el-button>
            <el-button type="text" v-if="row.state===options.stateEnum.REJECT" @click="goEdit(row)">编辑</el-button>
            <el-button type="text" v-if="row.state===options.stateEnum.WAIT_APPROVAL" @click="goExamine(row)">审核</el-button>
            <el-button type="text" v-if="row.state===options.stateEnum.REJECT" @click="showRejectReson(row)">审批意见</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="yema">
        <div>
            总共 {{ pagination.total }} 条&nbsp;&nbsp;第 {{ pagination.currentPage }} / {{ pagination.pageCount || (pagination.pageSize ? Math.ceil((pagination.total || 1)
              /
              pagination.pageSize) : 1) }} 页
        </div>
        <el-pagination :current-page="pagination.currentPage" :page-size="pagination.pageSize" :total="pagination.total"
          :pager-count="pagination.pagerCount || 7" :page-sizes="[10, 20, 50, 100]" small class="pagination-pager"
          layout="slot, prev, pager, next, sizes, jumper" @current-change="currentChange" @size-change="sizeChange">
        </el-pagination>
      </div>
    </div>
    
    <SelectProject ref="selectProjectRef" :projectWorkTypeOptions="options.projectWorkTypeOptions"/>
  </div>
  <edit-dialog tilte="驳回" :centerDialogVisible="showRejectVisible" width="500" @Cancel="showRejectVisible=false" :defaultButton="false">
      <template #content>
        <div style="padding: 0 20px;">
          <el-row>
          <el-col :span="5">审批意见：</el-col>
          <el-col :span="19">{{ rejectReson }}</el-col>
        </el-row>
        </div>
      </template>
      <template #custom>
        <el-button @click="showRejectVisible=false">关闭</el-button>
      </template>
    </edit-dialog>
</template>

<script>
import router from '@/router'
// import EditDialog from "@/components/editDialog/index.vue";
import EditDialog from "../../event/components/modal.vue";
import {exportProjectList, getProjectConditionsStatNum, getApplyPageList} from "@/api/construction-daily/daily";
import {getResource} from "@/api/resource";
import { dicFormatter, stateEnum,stateOptions } from "@/views/construction/project-daily/projectUtil";
import {dayjs, ElMessage } from "element-plus";
import store from "@/store";
import SelectProject from './components/SelectProject';

export default {
  // name: "ProjectApplicationList",
  components: {
    SelectProject, EditDialog
  },
  data() {
    return {
      // pageType: ProjectListType.LIST,
      myTooltip: {
        width: '500px'
      },
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      searchForm: {
        condition: {},
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableData: [],

      options: {
        locationO: [],
        projectTypeO: [],
        stateOptions,
        stateEnum: stateEnum,
        projectWorkTypeOptions: [], // 涉及作业类型
        projectWorkTypeTreeProps: {
          label: 'label',
          // disabled: (data, node) => {
          //   return data.children
          // }
        },
      },
      dicFormatter,
      locationNumTotal:0,
      projectTypeNumTotal:0,
      // emergencyRepair:0,
      isShowTooltip: false,
      exportLoading:false,

      isIndeterminateProjectType: false,
      checkAllProjectType: false,

      isIndeterminateLocation: false,
      checkAllLocation: false,
      showRejectVisible:false,
      rejectReson: '',
    }
  },
  provide() {
    return {
      options: this.options
    }
  },
  created() {
    // this.initQuery()
    this.initOptions()
    this.getList()
  },
  methods: {
    showRejectReson(row){
      this.rejectReson=row.reasonRejection
      this.showRejectVisible=true;
    },
    handleCheckAllChangeProjectType(value) {
      let all = this.options.projectTypeO.map(item => item.value)
      this.searchForm.condition.projectType = value ? all : [];
      this.isIndeterminateProjectType = false;
    },
    handleCheckedChangeProjectType(value) {
      let total = this.options.projectTypeO.length
      let checkedCount = value.length;
      this.checkAllProjectType = checkedCount === total;
      this.isIndeterminateProjectType = checkedCount > 0 && checkedCount < total;
    },


    handleCheckAllChangeLocation(value) {
      let all = this.options.locationO.map(item => item.value)
      this.searchForm.condition.location = value ? all : [];
      this.isIndeterminateLocation = false;
    },
    handleCheckedChangeLocation(value) {
      let total = this.options.locationO.length
      let checkedCount = value.length;
      this.checkAllLocation = checkedCount === total;
      this.isIndeterminateLocation = checkedCount > 0 && checkedCount < total;
    },

    onMouseOver(obj,str){
      let jiaTag = document.createElement('span');
      jiaTag.innerText=str;
      jiaTag.className='getWidth';
      document.querySelector('body').appendChild(jiaTag);
      let currentWidth = document.querySelector('.getWidth').offsetWidth;
      document.querySelector('.getWidth').remove();
      const cellwidth = obj.target.offsetWidth;
      if(currentWidth>=3*cellwidth){
        this.isShowTooltip=true
      }else{
        this.isShowTooltip = false
      }
    },
    findSpecialJobTypeName(typeList){
      const aa = typeList.map(item=>dicFormatter(this.options.projectWorkTypeOptions, item))
      return aa.join(',')
    },
    // initQuery() {
    //   this.pageType = this.$route.path === '/construction/project-review' ? ProjectListType.REVIEW_LIST : ProjectListType.LIST
    // },
    initOptions() {
      // const tree = store.getters['user/getOrganTree']
      // this.options.companyUnitTreeData = tree
      Promise.all([
        getResource('CM_PROJECT_TYPE'),
        getResource('terminals'),
        getResource('CM_PROJECT_WORK_TYPE'),
        getResource('CM_PROJECT_WORK_TYPE'),
      ]).then(([
                 res1,
                 res2,
                 CM_PROJECT_WORK_TYPE,
               ]) => {
        this.options.projectTypeO = [...res1.data.properties.meta,{
          label: '应急抢修',
          value: '4'
        }]
        this.options.locationO = res2.data.properties.meta
        this.options.projectWorkTypeOptions = CM_PROJECT_WORK_TYPE.data.properties.meta
         this.getStat()
      })
    },
    handleQuery() {
      this.pagination.currentPage=1;
      this.getStat()
      this.getList()
    },
    handleReset() {
      this.$refs.formRef.resetFields();
      this.pagination.currentPage=1;
      this.isIndeterminateProjectType = false
      this.isIndeterminateLocation = false

      this.checkAllProjectType = false
      this.checkAllLocation = false
      this.getList();
    },
    getList() {
      this.loading = true
      // this.getStat()
      this.searchForm.pageNum=this.pagination.currentPage;
      this.searchForm.pageSize = this.pagination.pageSize;
      const condition= JSON.parse(JSON.stringify(this.searchForm.condition))
      const {applyTime,projectType, location,specialJobType} = condition;
      if (applyTime?.length > 0) {
        condition.startTime = applyTime[0] + ' 00:00:00'
        condition.endTime = applyTime[1] + ' 23:59:59'
      } else {
        condition.startTime=undefined;
        condition.endTime=undefined;
      }
      if(specialJobType?.length===0){
        condition.specialJobType=undefined
      }
      // if(projectType==='4'){
      //  condition.projectId = null;
      // }
      if(projectType?.length===0){
        condition.projectType=undefined;
      }
      if(location?.length===0){
        condition.location=undefined;
      }
      getApplyPageList({...this.searchForm,condition}).then(res => {
        let {total, list} = res.data;
        const formatList=list.map(item=>{
          return {
            projectType: item.cmProject?item.cmProject.projectType: '应急抢修',
            projectName: item.cmProject?item.cmProject.projectName: '-',
            projectUnitName: item.cmProject?item.cmProject.projectUnitName: '-',
            projectNo: item.cmProject?item.cmProject.projectNo: '-',
            constructionOperationContent: item.constructionOperationContent,
            constructionChargePersonName: item.cmProject?item.cmProject.projectChargePersonName: '-',
            constructionUnitName: item.cmProject?item.cmProject.constructionUnitName: '-',
            specialJobType: item.specialJobType?.length>0?this.findSpecialJobTypeName(item.specialJobType):'-' , 
            applyTime: item.applyConstructionTime,
            state: item.state,
            id: item.id,
            projectId: item.projectId,
            applyNo: item.applyNo,
            reasonRejection: item.reasonRejection,
          }
        })
        this.tableData = formatList;
        this.pagination.total = total
      }).finally(() => {
        setTimeout(() => {
          this.loading = false
        }, 300)
      })
    },
    currentChange(currentPage){
      console.log(currentPage,'currentPage')
      this.pagination.currentPage=currentPage;
      this.getList();
    },
    sizeChange(pageSize){
      console.log(pageSize,'pageSize');
      this.pagination.currentPage = 1;
      this.pagination.pageSize = pageSize;
      this.getList();
    },
    // 获取角标
    getStat() {
      getProjectConditionsStatNum().then(res => {
      const {data}=res;
      this.locationNumTotal=data.t3 + data.t5;
      this.projectTypeNumTotal = data.all;
      console.log(this.options.locationO,'mlmlmlm')
      this.options.locationO.forEach(item=>{
        if(item.value==='T3'){
          item.num=data.t3
        }
        if(item.value==='T5'){
          item.num=data.t5
        }
      });
      this.options.projectTypeO.forEach(item=>{
        if(item.value==='1'){
          console.log('uuuuuuuuuu')
          item.num=data.projectApproved
        }
        if(item.value==='2'){
          item.num=data.temporary
        }
        if(item.value==='3'){
          item.num=data.maintenance
        }
        if(item.value==='4'){
          item.num=data.emergencyRepair
        }
      });
      
      })
    },
    // 跳转新增施工申请 打开项目选择
    goCreate() {
      this.$refs.selectProjectRef.openSelectProject()
    },
    
    // 查看
    goDetail(row) {
      // console.log(id,'kkkkk')
      router.push(`/construction/project-daily/detail?projectId=${row.projectId}&id=${row.id}`)
    },
    goEdit(row) {
      router.push(`/construction/project-daily/edit?projectId=${row.projectId}&id=${row.id}`)
    },
    goExamine(row){
      router.push(`/construction/project-daily/examine?projectId=${row.projectId}&id=${row.id}`)
    },

    // getSum(obj) {
    //   let values = Object.values(obj)
    //   let sum = 0
    //   values.forEach(item => sum += Number.parseInt(item))
    //   return sum
    // },
    handleExportList() {
      this.exportLoading=true;
      exportProjectList(this.searchForm.condition)
        .then( res => {
          const link = document.createElement('a')
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute(
            'download',
            `每日施工申请${dayjs().format('YYYY-MM-DD')}.xlsx`
          )
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
        .catch( err => {
          const reader = new FileReader();
          reader.readAsText(err,'utf-8');
          reader.onload=()=>{
            const json = JSON.parse(reader.result);
              ElMessage.error(json?.message || '导出失败')
            try{
              const json = JSON.parse(reader.result);
              ElMessage.error(json?.message || '导出失败')
            } catch(e){
              cons.log(e,'e')
            } 
          }
        })
        .finally(()=>{
          this.exportLoading = false;
        })
    }
    
  },
}
</script>
<style lang="less" scoped>
.hide{
  display: -webkit-box;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  white-space: pre-line;
}


.myPage {
  padding: 0 20px 20px 20px;
  box-sizing: border-box;
  .row {
    box-sizing: border-box;
    padding: 20px;
    background: white;
    margin-top: 12px;
    border-radius: 5px;
  }

  .search-row {
    padding: 20px 20px 10px !important;
    display: flex;
    .btnBox{
      width: 280px;
      display: flex;
      flex-wrap: nowrap;
      align-items: flex-end;
      padding-bottom: 24px;
    }
  }

  .table-row {
    display: flex;
    flex-direction: column;
    .table-head {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
  }

  .project-application-table {
    --el-table-header-bg-color: #F3F4F7;
    --el-table-header-text-color: #353A42;
    --el-table-row-hover-bg-color: #ebf7ff;
    --el-table-text-color: #535862;
    

    &.el-table--large {
      .el-table__header-wrapper {
        .el-table__cell {
          padding: 16px 0;
        }
      }

      .el-table__body-wrapper {
        .el-table__cell {
          padding: 15px 0;
        }
      }
    }
  }
}
.yema{
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  box-sizing: border-box;
  // padding-top: 20px;
  background-color: #ffffff;
}

.pagination-pager {
  margin-top: 20px;
  justify-content: flex-end;

  /deep/.el-pager li {
    font-size: 14px;
  }

  /deep/.el-pager li.is-active {
    background: #e0f2ff;
  }

  /deep/.el-pager li.is-active:hover {
    background: #e0f2ff;
  }

  /deep/.el-pager li:hover {
    background: #f3f3f6;
  }

  /deep/.el-pagination__editor.el-input {
    width: 48px;
    height: 32px;
  }

  /deep/.el-select .el-input {
    height: 32px;
    width: 98px;
  }
}
</style>
